//
//  PhotoBrowserViewController.swift
//  weibopush
//
//  Created by 龚欣 on 15/7/3.
//  Copyright © 2015年 gong. All rights reserved.
//

import UIKit
import FFAutoLayout
import SVProgressHUD

let GXPhotoCellReuseIdentifier = "GXPhotoCellReuseIdentifier"

class PhotoBrowserViewController: UIViewController,UICollectionViewDataSource,photoBrowerCellDelegate {
    
    var imageURLS : [NSURL] {
        didSet{
        
        }
    }
    
    override func loadView() {
        let frame = CGRectMake(0, 0, UIScreen.mainScreen().bounds.size.width + 20, UIScreen.mainScreen().bounds.size.height)
         view = UIView(frame: frame)
    }
    
    init(imageUrls : [NSURL],index : Int){
        // 这个快速构造方法为什么要调用super.init(nibName: nil, bundle: nil)，因为是The designated initializer.
        self.imageURLS = imageUrls
        imageIndex = index
        super.init(nibName: nil, bundle: nil)
        
        view.backgroundColor = UIColor.blackColor()
        setUpUI()
    }
    
    func setUpUI(){
        view.addSubview(collectionView)
        view.addSubview(closeBtn)
        view.addSubview(saveBtn)
        
        closeBtn.addTarget(self, action: "close", forControlEvents: UIControlEvents.TouchUpInside)
        saveBtn.addTarget(self, action: "savePhoto", forControlEvents: UIControlEvents.TouchUpInside)
        
        closeBtn.ff_AlignInner(ff_AlignType.BottomLeft, referView: view, size: CGSizeMake(60, 40), offset: CGPoint(x: 10, y: 0))
        saveBtn.ff_AlignInner(ff_AlignType.BottomRight, referView: view, size: CGSizeMake(60, 40), offset: CGPoint(x: -30, y: 0))
        collectionView.ff_Fill(view)
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        //跳到指定页面写在这里会崩
//        let idxPath = NSIndexPath(forItem: imageIndex, inSection: 0)
//        collectionView.scrollToItemAtIndexPath(idxPath, atScrollPosition: UICollectionViewScrollPosition.Bottom, animated: false)
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        //写在这个方法里面，会先显示第一张然后再跳到指定的页面
//        let idxPath = NSIndexPath(forItem: imageIndex, inSection: 0)
//        collectionView.scrollToItemAtIndexPath(idxPath, atScrollPosition: UICollectionViewScrollPosition.CenteredHorizontally, animated: false)
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        prepareCollectionView()
        
        let idxPath = NSIndexPath(forItem: imageIndex, inSection: 0)
        collectionView.scrollToItemAtIndexPath(idxPath, atScrollPosition: UICollectionViewScrollPosition.CenteredHorizontally, animated: false)
    }
    // MARK: 设置collectionView属性
    func prepareCollectionView(){
        flowLayout.itemSize = collectionView.bounds.size
        flowLayout.minimumInteritemSpacing = 0
        flowLayout.minimumLineSpacing = 0
        flowLayout.scrollDirection = UICollectionViewScrollDirection.Horizontal
        
        collectionView.registerClass(PhotoBrowerCell.self, forCellWithReuseIdentifier: GXPhotoCellReuseIdentifier)
        collectionView.backgroundColor = UIColor.clearColor()
        collectionView.pagingEnabled = true
        collectionView.dataSource = self
    }
    // MARK: collectionView数据源方法
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return imageURLS.count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(GXPhotoCellReuseIdentifier, forIndexPath: indexPath) as! PhotoBrowerCell
        cell.backgroundColor = UIColor.clearColor()
        cell.imageURL = imageURLS[indexPath.item]
        cell.photoCellDelegate = self
        
        return cell
    }
    // MARK:photoBrowerCellDelegate代理方法
    func photoBrowerCellIconDidTap() {
        close()
    }
    
    func photoBrowerDidEndZoom() {
        if photoScale < 0.8 {
            completeTransition(true)
        }else{
            view.transform = CGAffineTransformIdentity
            view.alpha = 1
            hideControl(false)
        }
    }
    
    func photoBrowerDidZoom(scale: CGFloat) {
        photoScale = scale
        if photoScale < 1.0 {
            startInteractiveTransition(self)
            hideControl(true)
        }else{
            hideControl(false)
        }
    }
    
    func hideControl(isHidden : Bool){
        view.backgroundColor = isHidden ? UIColor.clearColor() : UIColor.blackColor()
        saveBtn.hidden = isHidden
        closeBtn.hidden = isHidden
    }
    
    func currentImageIndex() -> Int{
       return collectionView.indexPathsForVisibleItems().last!.item
    }
    
    func currentImageView() -> UIImageView {
        let indexPath = collectionView.indexPathsForVisibleItems().last
        let cell = collectionView.cellForItemAtIndexPath(indexPath!) as! PhotoBrowerCell
        return cell.iconView
    }
    
    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    ///  MARK: 保存图片
    func savePhoto(){
       let indexPath = collectionView.indexPathsForVisibleItems().last!
        let cell = collectionView.cellForItemAtIndexPath(indexPath) as! PhotoBrowerCell
        let image = cell.iconView.image
        if image != nil{
            print(image)
            UIImageWriteToSavedPhotosAlbum(image!, self, "image:didFinishSavingWithError:contextInfo:", nil)
        }
    }
    
    func image(image : UIImage,didFinishSavingWithError error : NSError?,contextInfo: AnyObject){
        if error != nil{
            print(error)
            SVProgressHUD.showErrorWithStatus("保存失败")
            return
        }
        SVProgressHUD.showSuccessWithStatus("保存成功")
    }
    // MARK: 控制器dismiss方法
    func close(){
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    // MARK: 私有属性 和 控件懒加载
    private var imageIndex = 0
    
    lazy var closeBtn : UIButton = UIButton(title: "关闭", fontSize: 14)
    lazy var saveBtn : UIButton = UIButton(title: "保存", fontSize: 14)
    
    lazy var flowLayout = UICollectionViewFlowLayout()
    lazy var collectionView : UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: self.flowLayout)
    var photoScale : CGFloat = 0
}

extension PhotoBrowserViewController : UIViewControllerInteractiveTransitioning,UIViewControllerContextTransitioning{
    
    func startInteractiveTransition(transitionContext: UIViewControllerContextTransitioning) {
        view.transform = CGAffineTransformMakeScale(photoScale, photoScale)
        view.alpha = photoScale
        
    }
    
    func completeTransition(didComplete: Bool) {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    func containerView() -> UIView? {return self.view.superview}

    func isAnimated() -> Bool {return true}
    
    func isInteractive() -> Bool {return true}
    
    func transitionWasCancelled() -> Bool {return true}
    
    func presentationStyle() -> UIModalPresentationStyle {return UIModalPresentationStyle.Custom}
    

    func updateInteractiveTransition(percentComplete: CGFloat) {}
    func finishInteractiveTransition() {}
    func cancelInteractiveTransition() {}

    

    func viewControllerForKey(key: String) -> UIViewController? {return self}

   
    func viewForKey(key: String) -> UIView? {return self.view}
    
    func targetTransform() -> CGAffineTransform {return CGAffineTransformIdentity}
    

    func initialFrameForViewController(vc: UIViewController) -> CGRect {return CGRectZero}
    func finalFrameForViewController(vc: UIViewController) -> CGRect {return CGRectZero}

}
